import { fetchData } from '.';
import * as cheerio from 'cheerio';

export async function scrapePoemId(url: string): Promise<string[]> {
  try {
    const html: string | Buffer = await fetchData(url);
    if (html) {
      const $ = cheerio.load(html);

      const results = [];
      const mainElement = $('.space-y-4.p-4'); // 获取目标节点
      mainElement.children('section').each((index, element) => {
        const resurl = $(element)
          .find('a.pointer-events-auto.absolute.left-0.top-0.h-full.w-full')
          .attr('href'); // 获取h2内容
        results.push(resurl); // 添加到结果数组
      });

      // eslint-disable-next-line @typescript-eslint/no-unsafe-return
      return results;
    }
  } catch (error) {
    throw Error(error);
  }
}

type PoemProps = {
  title: string;
  dynasty: string;
  author: string;
  content: string;
  tagNames: string[];
  translation: string;
  notes: Record<string, string>;
};
export async function scrapePoemContent(url: string): Promise<PoemProps> {
  try {
    const html: string | Buffer = await fetchData(url);
    if (html) {
      const $ = cheerio.load(html);

      const poemContentNode = $('article').eq(0); // 获取内容
      const poemAboutNode = $('article').eq(1); // 获取关于诗词的节点
      const result: PoemProps = {
        title: '',
        dynasty: '',
        author: '',
        content: '',
        tagNames: [],
        translation: '',
        notes: {},
      };
      poemContentNode.children('div').each((index, element) => {
        result.title =
          result.title + $(element).children('h1').find('ruby').text();
        result.dynasty = $(element)
          .find('p.my-4.text-center.text-2xl')
          .contents()
          .eq(0)
          .text()
          .trim();
        result.author = $(element)
          .find('p.my-4.text-center.text-2xl a')
          .text()
          .trim();

        $(element)
          .find('p[class*="shi"]')
          .each((i, pElement) => {
            const rubyText = $(pElement).find('ruby').text().trim();
            if (rubyText) {
              result.content = result.content + rubyText;
            }
          });
      });

      const tagNodes = poemAboutNode.children().eq(0);
      tagNodes.children('a').each((index, element) => {
        result.tagNames.push($(element).text().trim());
      });
      const translationNodes = poemAboutNode.children().eq(1);
      translationNodes.children('p').each((index, element) => {
        result.translation = `${result.translation}\n${$(element).text().trim()}`;
      });

      const scripts = $('script').toArray();
      let anchorIndex = -1;

      // 寻找最后一个包含 self.__next_f.push([1, ""]) 的 script
      scripts.forEach((script, i) => {
        const content = $(script).html()?.trim();
        if (content === 'self.__next_f.push([1,""])') {
          anchorIndex = i;
        }
      });

      // 获取目标 script（anchorIndex - 2）
      const targetScript = anchorIndex >= 2 ? scripts[anchorIndex - 2] : null;
      const scriptContent = targetScript ? $(targetScript).html()?.trim() : '';
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
      result.notes = getContent(scriptContent);
      return result;
    }
  } catch (error) {
    console.log(error);
  }
}

function getContent(scriptContent: string) {
  try {
    if (!scriptContent) return null;

    const cleanedContent = scriptContent
      .replace(/^self\.__next_f\.push\(/g, '')
      .replace(/\)$/g, '');

    try {
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
      const jsonMatch = JSON.parse(cleanedContent);
      console.log('---', jsonMatch);

      if (!jsonMatch) return null;
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
      const annotationStr = jsonMatch[1]
        .replace(/^[^:]*:/, '')
        // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
        .match(/"annotation":(null|\{[^{}]*\})/);
      console.log(annotationStr);
      // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
      let res = {};
      // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
      if (annotationStr) {
        try {
          // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
          res = JSON.parse(annotationStr);
        } catch (e) {
          res = {};
          console.error('Error parsing annotation:', e);
        }
      }

      // eslint-disable-next-line @typescript-eslint/no-unsafe-return
      return res;
    } catch (e) {
      console.error('Error parsing JSON:', e);
      return null;
    }
  } catch (error) {
    console.error('Error in getContent:', error);
    return null;
  }
}
